package answer

import (
	. "whoops/leetcode/common"
)

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func removeNthFromEnd(head *ListNode, n int) *ListNode {
	//计算链表长度
	curr := head
	nodeLen := 0
	for curr != nil {
		curr = curr.Next
		nodeLen++
	}

	curr = head
	needLen := nodeLen - n - 1
	for needLen > 0 {
		curr = curr.Next
		needLen--
	}
	if needLen < 0 {
		head = head.Next
		return head
	}
	if curr.Next != nil {
		next := curr.Next.Next
		curr.Next.Next = nil
		curr.Next = next
	} else {
		curr = nil
	}
	return head
}
